package me.sdau.spider.openapi.comm.utils;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import io.jsonwebtoken.Claims;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * @author zj
 * @date 2018/3/26 14:48
 */
public class SystemUtil {

    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static Claims getClaims() {
        return (Claims) getAuthentication().getPrincipal();
    }

    public static List<String> getApis() {
        return Lists.newArrayList(Splitter.on(";")
                .omitEmptyStrings()
                .trimResults()
                .split((String) getClaims().get("api")));
    }

    public static Optional<HttpServletRequest> getRequest() {
        try {
            return Optional.of(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        } catch (Exception e) {
            return Optional.empty();
        }
    }

    public static String getURI() {
        if (getRequest().isPresent()) {
            return getRequest().get().getRequestURI();
        }
        return "";
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr() {
        if (!getRequest().isPresent()) {
            return "";
        }
        HttpServletRequest request = getRequest().get();
        String remoteAddr = request.getHeader("X-Real-IP");
        if (Strings.isNullOrEmpty(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (Strings.isNullOrEmpty(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (Strings.isNullOrEmpty(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }

    /**
     * 转换为时间（天,时:分:秒.毫秒）
     * @param timeMillis
     * @return
     */
    public static String formatDateTime(long timeMillis){
        long day = timeMillis/(24*60*60*1000);
        long hour = (timeMillis/(60*60*1000)-day*24);
        long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
        long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
        long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
        return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
    }
}
